#include "StdAfx.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include "Subtractive.h"
#include <cmath>
#include <vector>
#include <string>


CSubtractive::CSubtractive(void)
{
	m_type = L"saw";
	m_pitch = 1.0;
	m_time = 0.0;
}


CSubtractive::~CSubtractive(void)
{
}

void CSubtractive::Start()
{
	const int QUEUESIZE = 3;
	const double DELAY = 1.0;

    m_phase = 0;
	m_wrloc = 0;

	m_yqueue.resize(QUEUESIZE);

	m_r = 1 - (m_bandwidth/2.0);


}

bool CSubtractive::Generate()
{
	const int QUEUESIZE = 3;

	std::vector<double> wavetable;

	wavetable = m_wavetable;

    double sample = 0.0;
	double outaudio = 0.0;
	double filter = m_frequency - ((m_time/m_duration)*m_frequency);
	double costheta = ((2.0*m_r) * cos(2.0*3.14*filter))/(1.0 + (m_r*m_r));
	double a = (1 - (m_r*m_r)) * (sqrt(1.0 - (costheta*costheta)));

	int cycle_size = int((44100.0 / 440.0) + 0.5);
	int count = int(m_phase * m_pitch) % cycle_size;



    sample = wavetable[count];
		             
	m_wrloc = (m_wrloc + 1) % QUEUESIZE;

	outaudio = a * sample + ((2.0 * a * costheta) * m_yqueue[(m_wrloc+QUEUESIZE-1) % QUEUESIZE]) - ((m_r * m_r) * m_yqueue[(m_wrloc+QUEUESIZE-2) % QUEUESIZE]);

	m_yqueue[m_wrloc] = outaudio;

    mFrame[1] = mFrame[0] = outaudio;
    m_phase++;
	m_time += GetSamplePeriod();

    return true;
}